<#include "/layout/layout.ftl">
<#import "/layout/macro.ftl" as macro>
<#import "/layout/select.ftl" as my/>
<#assign css>
	<style>
		#content{
			width: 100%;
			height: 650px;
		}
        .box-body small{
            font-size:100%;
        }
        .list-group-item .badge{
            height:20px;
            line-height: 13px;
            cursor: pointer;width:50px;
        }
        .order-pool{
            border-top:1px solid #c9c9c9;
        }

		.selected-order{
			box-shadow: 0 0 10px #f00
		}
		.box-body small a{
			color:white;
		}
		.list-group-item.active, .list-group-item.active:hover, .list-group-item.active:focus {
			background-color: #3c8dbc !important;
			border-color: #3c8dbc !important;;
		}

        .amap-icon img{
            width: 38px;
            height: 48px;
        }
	</style>
</#assign>
<#assign js>
	<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.8&key=ec50062630c374925ce2ed4c2216c74f&plugin=AMap.Geocoder,AMap.Riding"></script>
<script>
	//初始化地图插件
    var map = null;
    var tempOderId = null;
    var tempDispatchType = "${agent.dispatchType !}";
    var markers = [];
    var riding = null;//骑行路线
	window.onload = function(){
		map = new AMap.Map('content',{
            resizeEnable: true, //是否监控地图容器尺寸变化
            zoom: 13, //初始地图级别
		});
		var address = "${agent.name!}";
		if(address){
            geoCode(address,function(aa){
                //alert(aa);
                //selectMaster('1');//标注所有待接单状态的骑手（跑腿）
			});
		}
	}

	setTimeout(function(){
        location.reload();
    },50000);

	//派单
	function dispatch(orderId, masterId, masterName) {
		layer.confirm('确定将此订单派送给'+masterName+'师傅吗?', {orderId: orderId, masterId: masterId}, function (index) {
			$.ajax({
				type: "POST",
				dataType: "json",
                data:{orderId: orderId, masterId: masterId},
				url: "/orderDispatch/dispatch/",
				success: function (res) {
					layer.msg(res.message, {time: 2000}, function () {
						location.reload();
					});
				},
                error:function(res){
                    layer.msg("派单失败")
                    //alert("派单失败:"+JSON.stringify(res));
                }
			});
		});
	}

    //修改派单方式
    function dispatchType(dispatchType) {
	    if(!dispatchType){
	        layui.msg("数据错误");
	        return false;
        }
        //layer.confirm('确定修改派单方式吗?', {dispatchType:dispatchType}, function (index) {
            $.ajax({
                type: "POST",
                dataType: "json",
                data:{dispatchType:dispatchType},
                url: "/orderDispatch/dispatchType",
                success: function (res) {
                    layer.msg(res.message, {time: 2000}, function () {
                        location.reload();
                    });
                },
                error:function(res){
                    layer.msg("派单失败")
                    //alert("派单失败:"+JSON.stringify(res));
                }
            });
        //},function(){
         //   debugger;
        //    if(dispatchType == 'auto'){
       //         $("#person").attr("checked","checked");
        //    }else{
        //        $("#auto").attr("checked","checked");
       //     }

      //  });
    }



	$(function() {

		//单击订单
        $(".list-group").click(function (e){
            if($(this).hasClass("selected-order")){
                $(this).removeClass("selected-order");
                tempOderId = null;
                removeMarkers();
			}else{
                //是否已经派单
                var audio = $(this).data("audio");
                if(audio ==1){
                    layer.msg("已经派过单了！");
                    return;
                }

                $(".selected-order").removeClass("selected-order");
                $(this).addClass("selected-order");
                debugger;
                tempOderId = $(this).data("orderid");
                var fromlng = $(this).data("fromlng");
                var fromlat = $(this).data("fromlat");
                var tolng = $(this).data("tolng");
                var tolat = $(this).data("tolat");
                var type = $(this).data("type");
                var childType = $(this).data("childtype");
                //查看路径
                if(fromlng != null && fromlat != null && tolng != null && tolat != null  && fromlng != "" && fromlat != "" && tolng != "" && tolat != "") {
                    ridings(fromlng, fromlat, tolng, tolat);
                }
                //匹配师傅
                if(type != null && childType != null && fromlng != null && fromlat != null && tolng != null && tolat != null && fromlng != "" && fromlat != "" && tolng != "" && tolat != "" ){
                    selectMasterAll(type,childType,fromlng,fromlat, tolng, tolat)
                }else{
                    if(type != null && childType != null && fromlng !=null && fromlng != "" && fromlat != ""){
                        selectMaster(type,childType,fromlng,fromlat)
                    }else if(type != null && childType != null && tolng !=null && tolng != "" && tolat != ""){
                        selectMaster(type,childType,tolng,tolat)
                    }
                }
			}
        });
		//查看路径
        $(".show-path").click(function (e){

            var fromlng = $(this).data("fromlng");
            var fromlat = $(this).data("fromlat");
            var tolng = $(this).data("tolng");
            var tolat = $(this).data("tolat");
            if(fromlng == null || fromlat == null || tolng == null || tolat == null ){
                //layer.msg("123");
			}else{
                ridings(fromlng,fromlat,tolng,tolat)
                //var useScope = e.currentTarget.value;
			}
        });
		//切换派单方式
        $(".dispathType").click(function (e){
            var temp = $(this).val();
            if(temp != tempDispatchType){
                dispatchType(temp);
            }
        });
	});

    /**
     * 查询师傅数据
     * 只有起或始地址的订单
     * @param type
     *
     */
    function selectMaster(type,childType, longitude, latitude){
        //var childType = $("#childType");
        $.ajax({
            type: "GET",
            url: "/orderDispatch/selectMaster?type="+type+"&childType="+childType+"&longitude="+longitude+"&latitude="+latitude,
            dataType: "JSON",
            success: function(res){
                if(res != null && res.data != null){
                    for(var i=0;i<res.data.length;i++){
                        makeMaster(res.data[i].masterId,res.data[i].longitude,res.data[i].latitude,res.data[i].masterName, res.data[i].orderCount, res.data[i].path);
                    }
                }
            }
        });
    }

    /**
     * 查询师傅数据
     * 有起始地址的订单
     * @param type
     *
     */
    function selectMasterAll(type,childType,fromLongitude,fromLatitude, toLongitude, toLatitude){
        //var childType = $("#childType");
        $.ajax({
            type: "GET",
            url: "/orderDispatch/selectMasterAll?type="+type+"&childType="+childType+"&fromLongitude="+fromLongitude+"&fromLatitude="+fromLatitude+"&toLongitude="+toLongitude+"&toLatitude="+toLatitude,
            dataType: "JSON",
            success: function(res){
                if(res != null && res.data != null){
                    for(var i=0;i<res.data.length;i++){
                        makeMaster(res.data[i].masterId,res.data[i].longitude,res.data[i].latitude,res.data[i].masterName, res.data[i].orderCount, res.data[i].path);
                    }
                }
            }
        });
    }

    //删除所有标记
    function removeMarkers(){
        if(map !=null && markers!=null && markers.length > 0){
            map.remove(markers);
        }
        if(riding != null){
            riding.clear();
        }
    }
    //获取分站的经纬度
    var geocoder,marker;
    function geoCode(address,callback) {
        if(!geocoder){
            geocoder = new AMap.Geocoder({
                //city: "010", //城市设为北京，默认：“全国”
            });
        }
        geocoder.getLocation(address, function(status, result) {
            if (status === 'complete'&&result.geocodes.length) {
                var lnglat = result.geocodes[0].location;
                //alert(lnglat);
                //debugger;
                //document.getElementById('lnglat').value = lnglat;
                if(!marker){
                    marker = new AMap.Marker();
                    map.add(marker);
                }
                marker.setPosition(lnglat);
                map.setFitView(marker);
                map.setZoom(13);
                if(callback){
                    callback(lnglat);
				}
            }else{
                alert(JSON.stringify(result))
            }
        });
    }

    //骑行路径规划、
    function ridings(fromlng,fromlat,tolng,tolat){
        var ridingOption = {
            map: map,
            panel: "panel",
            policy: 1,
            hideMarkers: false,
            isOutline: true,
            outlineColor: '#ffeeee',
            autoFitView: true
        }
        //骑行导航
        riding = new AMap.Riding(ridingOption);
        //根据起终点坐标规划骑行路线
        riding.search([fromlng,fromlat],[tolng,tolat], function(status, result) {
            // result即是对应的骑行路线数据信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_RidingResult
            if (status === 'complete') {
                map.setZoom(13);
                console.log('绘制骑行路线完成')
            } else {
                console.log('骑行路线数据查询失败' + result)
            }
        });
	}

	//标记师傅
	function makeMaster(masterId, lng,lat, masterName, orderCount, path){
        var marker = new AMap.Marker({
            position: [lng,lat],
            icon: '/assets/img/master.png',
            //icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
            offset: new AMap.Pixel(-13, -30)
        });

        marker.setMap(map);

        // 设置鼠标划过点标记显示的文字提示
        marker.setTitle('提示信息');

        // 设置label标签
        // label默认蓝框白底左上角显示，样式className为：amap-marker-label
        marker.setLabel({
            offset: new AMap.Pixel(50, 10),  //设置文本标注偏移量
            content: "<div class='info'>"+(masterName==null?"":masterName)+"师傅 ,"+(orderCount>0?orderCount+"单 ":"空闲 ")+"<br/>路线相同度"+(path>0?path:"0")+"%</div>", //设置文本标注内容
            direction: 'right' //设置文本标注方位
        });
        //添加参数
        marker.projectId = masterId;
        marker.masterName = masterName;

        //点标注的点击事件
        marker.on('click', function(e) {
            //alert(e.target.projectId);
            console.log(e.target.projectId);
            var dispathType = $(".dispathType:checked").val();
            //alert(dispathType);
            if(dispathType == 'person' && tempOderId !=null){
                //人工加抢单
                dispatch(tempOderId, e.target.projectId, e.target.masterName);
            }else{
                layer.msg("师傅ID："+e.target.projectId);
            }
        });
        //删除时用
        markers.push(marker);

	}
</script>
</#assign>
<@layout title="订单调度台" active="orderDispatch">
	<!-- Content Header (Page header) -->
	<section class="content-header">
		<h1>
			<small>订单调度台</small>
		</h1>
		<ol class="breadcrumb">
			<li><a href="/"><i class="fa fa-home"></i> 管理后台</a></li>
			<li><a href="#"><i class="fa fa-list-ul"></i> 订单管理</a></li>
			<li class="active"><i class="fa fa-edit"></i>订单调度台</li>
		</ol>
	</section>
	<!-- Main content -->
	<section class="content">
		<div class="row">
			<div class="col-md-4">
				<!-- Default box -->
				<div class="box  box-primary">
					<form class="form-horizontal form-edit" method="post" action="">
						<div class="box-head">
							<h3 class="text-center">订单池</h3>
						</div>
						<div class="box-body order-pool">
							<#if pageInfo?? && (pageInfo?size > 0) >
								<#list pageInfo as item>
									<div class="list-group" data-orderid="${item.orderId !}" data-type="${item.orderType !}" data-audio="${item.audio !}" data-childtype="${item.orderChildType !}" data-fromlng="${item.fromLongitude !}" data-fromlat="${item.fromLatitude!}" data-tolng="${item.toLongitude!}" data-tolat="${item.toLatitude!}">
										<li class="list-group-item active"
                                        <#if item.audio?? && item.audio =='1' >
                                            style="background: #aaaaaa !important; border: 1px solid #aaa;"
                                        </#if>
                                        >
											<span class="badge"><a href="/order/detail/${item.orderId !}">详情</a></span>
											<h4 class="list-group-item-heading">${item.orderTypeName !}-${item.orderChildTypeName !}</h4>
											<small>
												￥${item.amount?string('0.00')!}&nbsp;&nbsp;${item.orderNo!}
                                                <#--<#if item.fromAddress?? && item.toAddress?? >
												    &nbsp;&nbsp;<a href="#" class="show-path"  data-fromlng="${item.fromLongitude !}" data-fromlat="${item.fromLatitude!}" data-tolng="${item.toLongitude!}" data-tolat="${item.toLatitude!}">查看路径</a>
                                                </#if>-->
                                            </small>
										</li>
                                        <#if item.orderType ==1 && item.orderChildType ==13 &&  !item.fromAddress?? >
                                            <li href="#" class="list-group-item">
                                                <h4 class="list-group-item-heading">起始地址：附近购买</h4>
                                            </li>
                                        <#elseif item.orderType !=1>
                                            <li href="#" class="list-group-item">
                                                <h4 class="list-group-item-heading">起始地址：无</h4>
                                            </li>
                                        <#else>
                                            <li href="#" class="list-group-item">
                                                <h4 class="list-group-item-heading">起始地址：${item.fromAddress !}</h4>
                                                <p class="list-group-item-text">${item.fromName !}&nbsp;&nbsp;${item.fromPhone !}</p>
                                            </li>
                                        </#if>

										<li href="#" class="list-group-item">
											<h4 class="list-group-item-heading">目标地址：${item.toAddress!}</h4>
											<p class="list-group-item-text">${item.toName !}&nbsp;&nbsp;${item.toPhone !}</p>
										</li>
									</div>
								</#list>
							<#else>
								<div class="list-group">
									<li href="#" class="list-group-item">
										<h4 class="list-group-item-heading">暂无数据</h4>
									</li>
								</div>
							</#if>
						</div>

						<#--<div class="box-footer">
							<button type="button" class="btn btn-default btn-back">返回</button>
						</div>
-->
					</form>
				</div>
				<!-- /.box -->
			</div>
			<div class="col-md-8">
				<!-- Default box -->
				<div class="box  box-primary">
					<form class="form-horizontal form-edit" method="post" action="">
						<div class="box-header">
							<form class="form-horizontal form-edit" method="post" action="/order/index" id="form">
								<div class="form-group">
									<label class="col-sm-2 control-label">派单方式：</label>
									<div class="col-sm-10">
                                        <label class="radio-inline">
                                            <input type="radio"  value="person" id="person" name="dispathType" class="dispathType" <#if agent?? && agent.dispatchType=='person'>checked</#if> >人工加抢单
                                        </label>
                                        <label class="radio-inline">
                                            <input type="radio"  value="auto" id="auto" name="dispathType" class="dispathType"  <#if agent?? && agent.dispatchType=='auto'>checked</#if> >自动派单
                                        </label>
									</div>

								</div>
							</form>
						</div>
						<div class="box-body" id="content">

						</div>
						<div id="panel">

						</div>
						<#--<div class="box-footer">
							<button type="button" class="btn btn-default btn-back">返回</button>
						</div>-->

					</form>
				</div>
				<!-- /.box -->
			</div>
		</div>
	</section>
	<!-- /.content -->
</@layout>